<template>
  <u-upload
    ref="uploadRef"
    :file-list="fileList"
    :action="uploadUrl"
    :auto-upload="!custom"
    :max-count="props.limit"
    :max-size="props.size * 1024 * 1024"
    :width="props.width"
    :height="props.height"
    :custom-btn="!!slots.default"
    :header="headers"
    :multiple="false"
    :preview-full-image="false"
    @on-success="onSuccess"
    @on-list-change="onListChange"
  >
    <template #addBtn>
      <slot name="default" />
    </template>
  </u-upload>
</template>

<script setup lang="ts">

import { ref } from 'vue'
import UUpload from '@/uni_modules/vk-uview-ui/components/u-upload/u-upload.vue'

const props = withDefaults(defineProps<{
  modelValue?: string | string[] | null
  size?: number
  limit?: number
  // 是否自定义上传, 如是通过 fileList 获取文件列表
  custom?: boolean
  fileList?: { url: string}[]
  width?: number
  height?: number
  types?: ('png'| 'jpg'| 'jpeg' | 'webp' | 'gif' | 'image')[]
}>(), {
  size: 5,
  limit: 1,
  custom: false,
  width: 200,
  height: 200,
  types: () => ['png', 'jpg', 'jpeg', 'webp', 'gif', 'image'],
})

const emits = defineEmits<{
  (event: 'update:modelValue', value: string | string[]): void
  (event: 'update:fileList', value: { url: string}[]): void
  (event: 'change', value: string | string[]): void
}>()

const slots = useSlots()
const permission = usePermission()

const headers = computed(() => ({
  Authorization: `Bearer ${permission.token}`,
}))

const uploadRef = ref<typeof UUpload['methods']>()
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadUrl: string = import.meta.env.VITE_APP_UPLOAD_API.startsWith('/') ? `${baseUrl}${import.meta.env.VITE_APP_UPLOAD_API}` : import.meta.env.VITE_APP_UPLOAD_API
const fileList = ref<{ url: string}[]>([])

watch(() => props.modelValue, () => {
  if (props.fileList) {
    return
  }
  if (!props.modelValue?.length) {
    fileList.value = []
    uploadRef.value?.clear()
    return
  }
  let list: string[]
  if (props.limit === 1) {
    list = Array.isArray(props.modelValue) ? props.modelValue?.slice(0, 1) : [props.modelValue]
  } else {
    list = Array.isArray(props.modelValue) ? props.modelValue : props.modelValue.split(',')
  }
  fileList.value = list.map((url) => ({
    url: url.startsWith('http') ? url : `${baseUrl}${url}`,
  }))
})

function onListChange(list: any) {
  if (props.custom) {
    emits('update:fileList', list)
  }
}

const emitChange = () => {
  const list = fileList.value.map((it) => (it.url?.startsWith(baseUrl) ? it.url.substring(baseUrl.length) : it.url))
  const value = Array.isArray(props.modelValue) ? list : list.join()
  emits('change', value)
  emits('update:modelValue', value)
  emits('update:fileList', fileList.value)
}
function onSuccess(res: any, index: number) {
  if (res.code === 200) {
    uploadRef.value?.clear()
    const info = { name: res.fileName, url: `${baseUrl}${res.fileName}` }
    if (props.limit === 1) {
      fileList.value = [info]
    } else {
      fileList.value.splice(index, 1, info)
    }
    emitChange()
  } else {
    uni.showToast({
      icon: 'none',
      title: res.msg,
    })
  }
}

</script>

<style scoped>

</style>
